package com.soywer.rpc.rpc05;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

import com.soywer.rpc.common.IUserService;
import com.soywer.rpc.common.User;

/**
 * 功能描述：
 *
 * @author 18065916_李猛
 * @since 2021/3/8
 */
public class Server {
    private static boolean running = true;
    public static void main(String[] args) throws Exception {

        //创建一个Socket服务端
        ServerSocket ss = new ServerSocket(8888);
        while (running) {
            Socket s = ss.accept();
            process(s);
            s.close();
        }
        ss.close();
    }

    private static void process(Socket s) throws Exception{
        InputStream in = s.getInputStream();
        OutputStream out = s.getOutputStream();
        //对象输入流-读取参数
        ObjectInputStream ois = new ObjectInputStream(in);
        //对象输出流-写对象
        ObjectOutputStream oos = new ObjectOutputStream(out);

        //方法名
        String methodName = ois.readUTF();
        //方法参数类型
        Class[] parameterTypes = (Class[])ois.readObject();
        //方法参数
        Object[] args = (Object[])ois.readObject();

        System.out.println("客户端要调用的方法名称：" + methodName);
        System.out.print("客户端要调用的方法参数类型：");
        for (Class parameterType : parameterTypes) {
            System.out.print(parameterType + "\t");
        }
        System.out.println();
        System.out.print("客户端要调用的方法参数：" + args);
        for (Object arg : args) {
            System.out.print(arg + "\t");
        }
        System.out.println();

        //实例化对象
        IUserService service = new UserServiceImpl();
        //获取需要调用的方法
        Method method = service.getClass().getMethod(methodName,parameterTypes);
        //执行该方法调用-传递实体及参数
        User user = (User)method.invoke(service,args);

        //对象输入流-写参数
        oos.writeObject(user);
        //数据输出流刷新
        oos.flush();
    }
}
